package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/dept")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    @RequestMapping("/list")
    @RequiresPermissions(value = {"部门列表权限","dept:list"},logical = Logical.OR)
    public String list(QueryObject queryObject, Model model) {

        PageInfo<Department> pageInfo = departmentService.selectByQo(queryObject);

        model.addAttribute("pageInfo", pageInfo);

        return "department/list";
    }

    @RequestMapping("/input")
    @RequiresPermissions(value = {"部门编辑权限","dept:input"},logical = Logical.OR)
    public String input(Long deptId, Model model) {
        if (deptId != null) {
            Department department = departmentService.selectBydeptId(deptId);
            model.addAttribute("department", department);
        }
        return "department/input";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"部门编辑或新增权限","dept:saveOrUpdate"},logical = Logical.OR)
    public JsonResult saveOrUpdate(Department department, Model model) {
        JsonResult result = new JsonResult();
        try {
            //int a = 1/0;
            departmentService.saveOrUpdate(department);
            //保存成功
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("保存失败");
        }
        return result;
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = {"部门删除权限","dept:delete"},logical = Logical.OR)
    public JsonResult delete(Long deptId) {
        JsonResult result = new JsonResult();
        try {
            if (deptId != null) {
                departmentService.deleteBydeptId(deptId);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("删除操作失败,请重试");
        }
        return result;
    }


}
